package com.core.springSecurity.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.ErrorCodeEnum;
import com.common.exception.BusinessException;
import com.common.utils.ServletUtils;
import com.common.utils.StringUtils;
import com.core.springSecurity.model.LoginUserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;


@Service("ss")
public class PermissionService
{

    /** 所有权限标识 */
    public static final String ALL_PERMISSION = "*:*:*";

    /** 管理员角色权限标识 */

    private static final String PERMISSION_DELIMETER = ",";

    public static final String SYSTEM_OPERATE_NAME ="系统操作权限";
    public static final String SYSTEM_OPERATE ="SYSTEM";

    public static final String OPERATE_ROLE_NAME ="后台用户权限";
    public static final String OPERATE_ROLE ="OPERATE_ROLE";

    public static final String SELECT_NAME ="查看权限";
    public static final String SELECT ="SELECT";


    /**
     * 日志权限模块
     * */
    public static final String LOG_SELECT_NAME = "查看日志权限";
    public static final String LOG_SELECT = "LOG_SELECT";


    private static final TreeMap<String,String> permissionMap = new TreeMap<>();

    @Resource
    private TokenService tokenService;

    static {
        permissionMap.put(SYSTEM_OPERATE, SYSTEM_OPERATE_NAME);
        permissionMap.put(OPERATE_ROLE,OPERATE_ROLE_NAME);
        permissionMap.put(SELECT,SELECT_NAME);
    }

    /**
     * @Author: zql
     * @Description: 获取权限列表
     * @Data: 2021-07-12
     */
    public static JSONArray getPermissionList(){
        JSONArray jsonArray=new JSONArray();
        for(String key:permissionMap.keySet()){
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("permissionName",permissionMap.get(key));
            jsonObject.put("permission",key);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
    /**
     * 验证是否有该权限关键字
     *
     * @param permissions 权限字符串
     */
    public static boolean hasPermission(Set<String> permissions){
        for(String permission:permissions){
           if(!permissionMap.containsKey(permission)) {
               return false;
           }
        }
        return true;
    }

    public static String getPermissionName(String permission){
        return permissionMap.get(permission);
    }

    /**
     * 验证用户是否具备某权限
     * 
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission)
    {
        if (StringUtils.isEmpty(permission))
        {
            throw new BusinessException(ErrorCodeEnum.NOT_FOUNT_PERMISSION);
           // return false;
        }
        LoginUserDetails loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions()))
        {
            throw new BusinessException(ErrorCodeEnum.NOT_FOUNT_USER_PERMISSION);
            //return false;
        }
        if(hasPermissions(loginUser.getPermissions(), permission)){
            return true;
        }
        throw new BusinessException(ErrorCodeEnum.INADEQUATE_PERMISSION);
    }

    /**
     * 验证用户是否不具备某权限，与 hasPermi逻辑相反
     *
     * @param permission 权限字符串
     * @return 用户是否不具备某权限
     */
    public boolean lacksPermi(String permission)
    {
        return !hasPermi(permission);
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表
     * @return 用户是否具有以下任意一个权限
     */
    public boolean hasAnyPermi(String permissions)
    {
        if (StringUtils.isEmpty(permissions))
        {
            throw new BusinessException(ErrorCodeEnum.NOT_FOUNT_PERMISSION);
        }
        LoginUserDetails loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions()))
        {
            throw new BusinessException(ErrorCodeEnum.NOT_FOUNT_USER_PERMISSION);
        }
        Set<String> authorities = loginUser.getPermissions();
        for (String permission : permissions.split(PERMISSION_DELIMETER))
        {
            if (permission != null && hasPermissions(authorities, permission))
            {
                return true;
            }
        }
        throw new BusinessException(ErrorCodeEnum.INADEQUATE_PERMISSION);
    }

    public boolean hasAnyPermi2(String... permissions)
    {
        if (StringUtils.isEmpty(permissions))
        {
            throw new BusinessException(ErrorCodeEnum.NOT_FOUNT_PERMISSION);
        }
        LoginUserDetails loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions()))
        {
            throw new BusinessException(ErrorCodeEnum.NOT_FOUNT_USER_PERMISSION);
        }
        Set<String> authorities = loginUser.getPermissions();
        for (String permission : permissions)
        {
            if (permission != null && hasPermissions(authorities, permission))
            {
                return true;
            }
        }
        throw new BusinessException(ErrorCodeEnum.INADEQUATE_PERMISSION);
    }


    /**
     * 判断是否包含权限
     * 
     * @param permissions 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(Set<String> permissions, String permission)
    {
        return permissions.contains(ALL_PERMISSION) ||
                permissions.contains(StringUtils.trim(permission));
    }
}
